import { MAP_TYPE, TENCENT_MAP_KEY } from '@/config/constant'
import QQMapWX from '@/utils/qqmap-wx-jssdk.min'
const qqmapsdk = new QQMapWX({
  key: TENCENT_MAP_KEY // 必填
})
let rejectedPrivacy = false // 拒绝隐私授权
let rejectedLocation = false // 拒绝地理位置授权

/**
 * 根据getLocation获取当前小程序用户的位置
 * @returns 位置
 */
export const getCurrentLocation = async () => {
  if (rejectedLocation) {
    try {
      await openSetting()
      rejectedLocation = false
      getCurrentLocation()
    } catch (err) {}
  } else {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: MAP_TYPE,
        success: res => {
          rejectedPrivacy = rejectedLocation = false
          resolve(res)
        },
        fail: err => {
          rejectedPrivacy = err.errno === 104
          rejectedLocation = err.errMsg === 'getLoaction:fail auth deny'
          if (rejectedLocation) {
            reject(err)
          } else {
            resolve({ longitude: '', latitude: '' })
          }
        }
      })
    })
  }
}

/**
 *
 * @param { 起点位置 } sLocation { latitude, longitude }
 * @param { 终点位置 } dLocation { latitude, longitude }
 * @param {*} mode 计算方式, 默认是直线距离
 * @returns 起点和终点距离
 */
export const getDistance = (sLocation, dLocation, mode = 'straight') => {
  return new Promise((resolve, reject) => {
    qqmapsdk.calculateDistance({
      mode, // 计算直线距离，不调用接口
      from: sLocation,
      to: [dLocation],
      success: res => {
        resolve(res.result.elements[0].distance)
      },
      fail: function (res) {
        reject(res)
      }
    })
  })
}

/**
 *
 * @param {*} 当前位置 { latitude, longitude }
 * @returns 当前位置地址
 */
export const getAddressByLocation = ({ latitude, longitude }) => {
  return new Promise((resolve, reject) => {
    const currentLocation = `${latitude},${longitude}`
    qqmapsdk.reverseGeocoder({
      location: currentLocation,
      success: res => {
        console.log(res.result)
        resolve(res.result.address)
      },
      fail: function (res) {
        reject(res)
      }
    })
  })
}

const TRY_MAX_NUM = 5
let n = 0 // 尝试开启startLocationUpdate次数
/**
 *
 * @param {*} 当前位置 { latitude, longitude }
 * @returns 当前位置地址
 */
export const startLocationUpdate = async callback => {
  if (rejectedLocation) {
    try {
      await openSetting()
      rejectedLocation = false
      startLocationUpdate(callback)
    } catch (err) {}
  } else {
    return new Promise((resolve, reject) => {
      if (n < TRY_MAX_NUM) {
        uni.startLocationUpdate({
          type: MAP_TYPE,
          success: () => {
            rejectedPrivacy = rejectedLocation = false
            uni.onLocationChange(callback)
            resolve()
          },
          fail: err => {
            if (err.errMsg === 'startLocationUpdate:fail auth deny' || err.errno === 104) {
              rejectedLocation = err.errMsg === 'startLocationUpdate:fail auth deny'
              rejectedPrivacy = err.errno === 104
              reject(new Error())
            } else {
              console.log(err)
              n++
              startLocationUpdate(callback)
            }
          }
        })
      } else {
        n = 0
        reject(new Error('微信版本太低，请升级'))
      }
    })
  }
}

export const jumpToTencentMap = async (latitude, longitude, name) => {
  if (rejectedLocation) {
    try {
      await openSetting()
      rejectedLocation = false
      jumpToTencentMap(latitude, longitude, name)
    } catch (err) {}
  } else {
    console.log(rejectedLocation)
    let plugin = requirePlugin('routePlan')
    let key = TENCENT_MAP_KEY //使用在腾讯位置服务申请的key
    let referer = '云瞳E服' //调用插件的app的名称
    let endPoint = JSON.stringify({
      name,
      latitude,
      longitude
    })
    uni.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint + '&navigation=' + 1
    })
  }
}

export const chooseUserLocation = async latlng => {
  if (rejectedLocation) {
    try {
      await openSetting()
      rejectedLocation = false
      chooseUserLocation(latlng)
    } catch (err) {}
  } else {
    let location = JSON.stringify(latlng)
    let key = 'HRRBZ-4C6C4-3HWUL-FVM4J-RMHL7-RDFL7' //使用在腾讯位置服务申请的key
    let referer = '云瞳运维' //调用插件的app的名称
    let category = '小区,生活服务'
    uni.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location' + location + '&category=' + category
    })
  }
}

function openSetting() {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '打开设置页面',
      content: '需要获取您的位置信息，请到小程序的设置页面中授权',
      success: res => {
        if (res.confirm) {
          uni.openSetting({
            success: res => {
              const userLocation = res.authSetting['scope.userLocation']
              if (typeof userLocation !== 'undefined' && userLocation) {
                resolve()
              } else {
                reject()
              }
            },
            fail: err => {
              reject(err)
            }
          })
        }

        if (res.cancel) {
          reject()
        }
      }
    })
  })
}
